package com.bdqn.springbootmybatisplus.controller;

import com.bdqn.springbootmybatisplus.mapper.SysUserMapper;
import com.bdqn.springbootmybatisplus.pojo.SysUser;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * IndexController
 *
 * @author f
 * @since 2021/12/9
 */
@Controller
public class IndexController {

    @Resource
    private SysUserMapper sysUserMapper;

    @RequestMapping("/login")
    public String toLogin(){

        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(Model model, HttpSession session, String usrName, String usrPassword){
        // 判断用户是否存在
        SysUser loginUser = sysUserMapper.login(usrName, usrPassword);
        // 用户密码不匹配
        if (loginUser == null){
            model.addAttribute("message","账号或密码错误，请重新登录。");
            return "login";
        }
        // 把用户保存到session中
        session.setAttribute("loginUser",loginUser);

        return "main";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        // 清除当前登录用户的Session
        session.removeAttribute("loginUser");
        session.invalidate();//销毁Session
        return "redirect:login";//最好重定向，保证 Cookie的删除
    }
    // （未成功的Shiro注销）
    // @RequestMapping("/logout")
    // public String logout(HttpSession session){
    //     session.removeAttribute("loginUser");
    //     SecurityUtils.getSubject().logout();//Shiro 注销
    //     return "redirect:login";//最好重定向，保证 Cookie的删除
    // }
}
